(function () {
  var yun = {};
  //分享内容
  var parm = {}

  /*字号rem尺寸变化代码*/
  // window.onload = window.onresize = function () {
  //     document.documentElement.style.fontSize = 100 * document.documentElement.clientWidth / 750 + 'px'
  // };
  //查看是否IOS
  var isIOS = navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;

  //获取路径参数
  function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }

  yun.ajax = function () {
    this.init.apply(this, arguments);
  };
  yun.ajax.prototype = {
    parm: {},
    //初始化请求，查找是否进行中的订单，有就跳转对应面对，并同时处理
    init: function () {
      var t = this;
      t.appid = arguments[0];
      t.key = 'fffa2a879e62e198924a95dc150dc33823bd0bf7abd3a20fff605f297ae9333804699723a6219048';
      t.token = arguments[1];
      var ph = window.location.href;
      var url = ''
      if (ph.indexOf('driver') > -1) {
        if (ph.indexOf('share_driver') > -1) {
          t.url = base + '/api/v1/driver/token/invite/driver'
        } else {
          t.url = base + '/api/v1/driver/token/share/info'
        }
      } else {
        t.url = base + '/api/v1/passenger/token/share/info'
      }

    },
    //初始化请求，查找是否进行中的订单，有就跳转对应面对，并同时处理
    init_ajax: function (cabk, error) {
      var t = this;
      t.ajax_md5(
        {
          token: t.token,
        },
        t.url,
        function (data) {
          var d = data.data;
          t.parm = {
            linkTitle: d.linkTitle,
            linkContent: d.linkContent,
            linkImg: d.linkUrl,
            linkUrl: d.linkUrl,
          };
          cabk(data);
        },
        function (data) {
          error(data);
        }
      )
    },
    /*
    * 算法逻辑
    * @（params）传入object 、字符串序列化、object FormData这三种参数，传入的数据格式决定了return的数据格式
    *      1: 参数数据类型的标记（paramsType）：
    *           字符串：1
    *           json对象：2
    *           FormData：3
    *      2: 处理参数成字符串
    *      3:增加md5验签逻辑(时间戳)
    *      4:对加密数据进行排序之前先拼上appid和token，排序完成后最后面拼上 key
    *      5:生成签名
    *      6:拼接随机数和签名，并返回最后的数据。
    * */
    md5: function (params) {
      var t = this;
      if (params === null) return null;
      //处理参数 如果传入的是字符串 则对
      var originalParamStr;
      var resultParam = params;
      var paramsType = 0;
      var paramsTypeStr = params.toString();
      if (typeof params === 'string') paramsType = 1; //string
      if ('[object Object]' === paramsTypeStr) {
        paramsType = 2;
      }
      ; //JSON对象
      if ('[object FormData]' === paramsTypeStr) {
        paramsType = 3
      }
      ; //FormData对象
      //不可处理的参数类型报错
      if (!paramsType) return 'parameterTypeError';

      //处理参数成字符串
      switch (paramsType) {
        case 1 : {
          originalParamStr = params;
          break;
        }
        case 2 : {
          originalParamStr = $.param(params);
          break;
        }
        case 3 : {
          var iterator = params.entries();
          var paramFormStr = '';
          //递归遍历
          var recursion_iterator = function (data) {
            if (data.done === false && !(data.value[1] instanceof File)) { //排除文件类型
              paramFormStr += (data.value[0] + '=' + data.value[1] + '&');
            }
            if (data.done === false) {
              recursion_iterator(iterator.next());
            }
          };
          recursion_iterator(iterator.next());
          if (paramFormStr.length > 0) paramFormStr = paramFormStr.substring(0, paramFormStr.length - 1);
          originalParamStr = paramFormStr;
          break;
        }
      }

      //1.中文解码 2.加号转换为空格
      originalParamStr = decodeURIComponent(originalParamStr).replace(/\+/g, " ");

      //增加md5验签逻辑
      var paramStr = '';
      var noncestr = new Date().getTime();

      var paramObject = {'noncestr': noncestr};
      var keyArray = ['noncestr'];
      var entryStrArray = originalParamStr.split('&');
      for (var i in entryStrArray) {
        var key = entryStrArray[i].split('=')[0];
        var value = entryStrArray[i].split('=')[1];
        if (key && value !== undefined && value !== '') {
          keyArray.push(key);
          paramObject[key] = value;
        }
        keyArray.sort();
      }
      for (var i in keyArray) {
        paramStr += (keyArray[i] + '=' + paramObject[keyArray[i]] + '&');
      }
      //拼上,appid,token
      paramStr = 'appid=' + t.appid + '&' + (paramStr || "") + 'token=' + t.token;

      //对加密数据进行排序
      function strToObj(str) {
        var obj;
        str = str.replace(/&/g, "','");
        str = str.replace(/=/g, "':'");
        str = "({'" + str + "'})";
        obj = eval(str);
        return obj;
      }

      paramStr = strToObj(paramStr);
      var kName = [], cParam = {};
      for (var ic in paramStr) {
        kName.push(ic);
      }
      kName.sort();
      for (var j in kName) {
        if (!!paramStr[kName[j]]) cParam[kName[j]] = paramStr[kName[j]];
      }
      window.dd = cParam;
      paramStr = decodeURIComponent($.param(cParam)).replace(/\+/g, " ");
      // 最后拼上key
      paramStr += '&key=' + t.key;
      console.log(paramStr);
      //生成签名
      // console.log('signStr:' + paramStr);
      // console.log(paramStr,CryptoJS.MD5(paramStr).toString());
      // console.log(paramStr);
      var sign = (CryptoJS.MD5(paramStr).toString()).toLocaleUpperCase();

      //签名完成后移除key参数
      paramStr = paramStr.substring(0, paramStr.lastIndexOf('&'));
      //拼接随机数和签名
      switch (paramsType) {
        case 1 : {
          resultParam = paramStr + ('&sign=' + sign) + ('&token=' + this.token);
          break;
        }
        case 2 : {
          resultParam['noncestr'] = noncestr;
          resultParam['sign'] = sign;
          resultParam['appid'] = t.appid;
          resultParam['token'] = t.token;
          break;
        }
        case 3 : {
          resultParam.append('noncestr', noncestr);
          resultParam.append('sign', sign);
          resultParam.append('token', t.token);
          resultParam.append('appid', t.appid);
          break;
        }
      }
      return resultParam;
    },
    //数据加密且执行请求
    ajax_md5: function (params, url, successCallBack, errorCallBack) {
      var t = this;
      // if(!t.token){layer.msg('网络延迟，请稍候请求');return ;}
      params = t.md5(params);
      if ('parameterTypeError' === params || params == false) {
        console.log('MD5签名：参数类型错误')
        return false;
      }
      this.ajax(params, url, successCallBack, errorCallBack)
    },
    //ajax封装
    ajax: function (params, url, successCallBack, errorCallBack, type) {
      var t = this;
      //var p = JSON.stringify(params);
      var ajaxObject = {
        type: !type ? 'POST' : type,
        url: url,
        data: params,
        dataType: 'json',
        cache: false,
        success: function (result) {
          //result=result.decryptRSA();
          //result=JSON.parse(result);
          if (result.success) {
            successCallBack(result);
          } else {
            errorCallBack(result);
          }
        },
        error: function (result) {
          var d;
          if (result.status == 200) {
            d = (result.responseText);
            d = JSON.parse(d);
            layer.msg(d.msg || '请求异常，请联系管理员');
            return;
          }
          showError('请求异常，请联系管理员');
        }
      };
      $.ajax(ajaxObject);
    }
  }
  //APP到h5采用的是url传参。
  var appid = GetQueryString('appid');
  var token = GetQueryString('token');
  var isopen = GetQueryString('isopen');
  // $('#header-url').find()
  events();
  $('.btn_close').click(function () {
    $('#declarationDialog').hide();
    $('#codeCOnDialog').hide();
    $('.mask').hide();
  });
  $('.huodong').click(function () {
    $('#declarationDialog').show();
    $('.mask').show();
  });
  if (isopen == 'false') {
    parm = linkCot;
    $('.invite').hide()
    $('#codeimg').css('visibility', 'hidden')
    $('#youhuij').css('visibility', 'hidden')
    return;
  }

  if (!token || !appid) {
    //alert('无效链接');
    //return;
  }

  var xuanxuan = new yun.ajax(appid, token);
  window.qrcode = new QRCode(document.getElementById('codeCOn'), {width: 250, height: 250});

  //司机邀请司机
  //if(window.location.href.indexOf('driver')>-1){
  xuanxuan.init_ajax(function (data) {
    var d = data.data;
    if (!d) {
      $('#codeimg').hide();
      parm = linkCot
      return;
    }
    //用户注册领取的时候动态显示可以领取金额的优惠券
    d.linkUrl = (d.linkUrl + '&i=' + d.inviteeMoney + '');
    if (!d.activeInfo) {
      parm = {
        linkTitle: d.linkTitle,
        linkContent: d.linkContent,
        linkImg: d.linkImg,
        linkUrl: d.linkUrl,
      }
    } else {
      parm = {
        linkTitle: d.activeInfo.linkTitle,
        linkContent: d.activeInfo.linkContent,
        linkImg: d.activeInfo.linkImg,
        linkUrl: d.activeInfo.linkUrl,
      }
    }
    var rewardMsg = ''
    if (window.location.href.indexOf('driver') > -1) {
      if (window.location.href.indexOf('share_driver') > -1) {//司机邀请司机
        rewardMsg = "00"
        driverS(d)
      } else {//司机邀请乘客
        if (d.getMode == 1) {
          rewardMsg += '<p>好友完成注册并首乘后</p>'
        }
        if (typeof d.awardAmount == 'number' && d.awardAmount != 0) {
          rewardMsg += '<p>您将获得' + d.awardAmount + '元现金奖励</p>'
        }
        if (d.invitedRewardMethod == 1) {
          rewardMsg += '<p>您的好友也可获得' + d.invitedGiftName + '</p>'
        } else if (d.invitedRewardMethod == 2) {
          rewardMsg += '<p>您的好友也可获得新人注册礼包</p>'
        } else if (d.invitedRewardMethod == 3) {
          rewardMsg += '<p>您的好友也可获得新人注册礼包和' + d.invitedGiftName + '</p>'
        }
        if (rewardMsg) {
          $('#youhuij').html(rewardMsg)
        }
        // $('#ccyy').html((d.awardAmount || '0') + '元现金奖励');
        // $('.xido').html(d.inviteeMoney || 0);
      }

    } else {//乘客邀请乘客
      if (d.getMode == 1) { // 新用户首单
        rewardMsg += '<p>好友完成注册并首乘后</p>'
        $('#guizenew').html('您邀请的新用户注册' + appName + '并完成首乘后，您也可获得邀请奖励')
      } else if (d.getMode == 2) { // 成功注册
        // rewardMsg+='好友注册成功'
        $('#guizenew').html('您邀请的新用户注册' + appName + '并完成首乘后，您也可获得邀请奖励')
      } else if (d.getMode == 3) { // 唤醒沉睡用户

      } else if (d.getMode == 4) { // 安慰连续叫单不成功用户

      } else if (d.getMode == 5) { // 安慰连续叫单不成功用户

      }
      if (typeof d.inviterMoney == 'number' && d.inviterMoney != 0) {
        rewardMsg += '<p>您将获得' + d.inviterMoney + '元优惠券</p>'
      }

      if (d.invitedRewardMethod == 1) {
        rewardMsg += '<p>您的好友也可获得' + d.invitedGiftName + '</p>'
      } else if (d.invitedRewardMethod == 2) {
        rewardMsg += '<p>您的好友也可获得新人注册礼包</p>'
      } else if (d.invitedRewardMethod == 3) {
        rewardMsg += '<p>您的好友也可获得新人注册礼包和' + d.invitedGiftName + '</p>'
      }
      if (rewardMsg) {
        $('#youhuij').html(rewardMsg);
      }
      // $('#ccyy').html((d.inviterMoney || '0') + '元优惠券');
      // $('.xido').html(d.inviteeMoney);
    }

    if (rewardMsg == "") {
      if (!d.linkUrl) { // 没有分享连接
        $('#codeimg').css('visibility', 'hidden')
        parm = linkCot
      } else {
        $('.code-img-msg').html('让朋友扫一扫')
        creanCode(parm.linkUrl);
      }
    } else {
      creanCode(parm.linkUrl);
    }

  }, function (data) {
    $('#codeimg').css('visibility', 'hidden')
    parm = linkCot
    events();

    // showError(data.msg)
  })
  //}

  ///司机邀请司机数据处理
  function driverS(data) {
    var a = data.activeInfo,
      il = data.inviteLog;

    // $('#youhuij').html('邀请好友入驻平台<br> <span style="font-size: .36rem;">邀请1个好友奖' + (a.awardAmount || '0') + '元</span>');
    if (il.inviteDriverList.length == 0) {
      return;
    }
    $('.history-tong').html('<p>已邀请 <span>' + il.inviteCount + '</span> 人</p><p class="hfenge"></p><p>已获得  <span>' + il.sumAwardAmount + '</span> 元</p>');
    var ht = '';
    for (var i = 0; i < (il.inviteDriverList).length; i++) {
      var ili = il.inviteDriverList[i];
      ht += '<li><p>' + ili.invitee + '</p><p>' + ili.createdOn + '</p></li>'
    }
    $('.history-ul').html(ht);
    $('#youhuij').hide();
    $('.l-history').show();
  }

  function creanCode(url) {
    qrcode.makeCode(url);
  }

  function events() {
    $('#we-chat').on('touchend', function () {
      //微信分享
      if (isIOS) {
        window.webkit.messageHandlers.wechat.postMessage(parm)
      } else {
        share.wechat(JSON.stringify(parm))
      }
    })
    $('#friends').on('touchend', function () {
      //朋友圈
      if (isIOS) {
        window.webkit.messageHandlers.friends.postMessage(parm)
      } else {
        share.friends(JSON.stringify(parm))
      }
    })
    $('#qq').on('touchend', function () {
      //QQ分享
      if (isIOS) {
        window.webkit.messageHandlers.qq.postMessage(parm)
      } else {
        share.qq(JSON.stringify(parm))
      }
    })
    $('#space').on('touchend', function () {
      // QQ空间分享
      // if (isIOS) {
      //     window.webkit.messageHandlers.spaceQ.postMessage(parm)
      // } else {
      //     share.spaceQ(JSON.stringify(parm))
      // }
      $('#codeCOnDialog').show();
      $('.mask').show();
    })
  }

//  显示历史收入
  $('#history-icon').click(function (event) {
    // alert(1)
    // $('.mask1').slideToggle();
    $('.history-con').slideToggle(300, function () {
      if ($('.history-con').is(':hidden')) {
        $('.mask').hide();
        $('#history-icon').removeClass("history-icon-up")
      } else {
        $('.mask').show();
        $('#history-icon').addClass('history-icon-up')
      }
    })
  })

//  显示错误
  var isShowError = false;

  function showError(text) {
    if (isShowError) {
      isShowError = true;
      return;
    }
    $(document).dialog({
      type : 'notice',
      infoText: '网络异常，请检查网络状态后重试',
      autoClose: 2500,
      position: 'center'  // center: 居中; bottom: 底部
    });
  }

  $('.ajaxError .abtns').click(function () {
    $('.ajaxError').hide();
    $('.mask').hide();
    isShowError = false;
  })
})();